package com.hjs.community.inform.controller;

import com.community.common.core.utils.Result;
import com.hjs.community.inform.config.DelayedConfig;
import com.hjs.community.inform.constant.RedisKey;
import com.hjs.community.inform.dto.SMSDto;
import com.hjs.community.inform.utils.SMSUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class SMSController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SMSUtils smsUtils;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public Result<Object> send(String mobile){

        //判断号码是否为空
        if (ObjectUtils.isEmpty(mobile)){
            return new Result<>().error("手机号为空");
        }
        //生成验证码
        String code = RandomStringUtils.random(4, false, true);
        //将验证码保存到redis中
        String key = String.format(RedisKey.LOGIN_SMS_KEY,mobile,code);
        redisTemplate.opsForValue().set(key,code,60, TimeUnit.SECONDS);
        //发送短信
        SMSDto smsDto = new SMSDto();
        smsDto.setMobile(mobile);
        smsDto.setCode(code);
        System.out.println("code====================="+code);
        //smsUtils.send(smsDto);
        //
        Long time = 10000l;

        return new Result<>().ViewOk(null);
    }
    @GetMapping("/delayedMessage")
    public String delayedMessage(String msg, Long time){
        rabbitTemplate.convertAndSend(DelayedConfig.YOUR_EXCHANGE_NAME, DelayedConfig.YOUR_ROUTING_KEY, msg, message -> {
            message.getMessageProperties().setHeader("x-delay", time);
            return message;
        });
        return "ok";
    }

}
